package service

import (
	"context"
	"github.com/micro/go-micro/v2/errors"
	"github.com/silenceper/wechat/v2/officialaccount/message"
	pb "micro-grpc-server/services/wechat/proto"
	"time"
)

func (s *WechatService) RobotReply(ctx context.Context, rq *pb.WechatReplyRequest, resp *pb.WechatReplyResponse) error {
	mp := s.dao.GetMp(rq.Scenario)
	if mp == nil {
		return errors.BadRequest(s.conf.ServerName, "%s 配置不存在", rq.Scenario)
	}

	//这个地方同时访问会出现问题 应该将参数附加到rq中
	//s.robot.ReplaceContent(mp.GetContext())
	var ch = make(chan *message.Reply, 1)
	s.robot.HandleRequest(rq, ch, mp.GetContext())

	// 3s中未处理完则直接先返回 后续使用客服消息回复 防止微信重复通知
	select {
	case r := <-ch:
		resp.Result = string(r.MsgType)
	case <-time.After(3 * time.Second):
		resp.Result = ""
	}
	close(ch)
	return nil
}
